package com.gwtt.simulator.netconf.framing;

import static com.gwtt.simulator.netconf.framing.Constant.*;

public class ChunkFramingMechanism implements NetconfEncoder{

    public String encode(String message) {
        StringBuilder chunkedMessage = new StringBuilder();
        int length = message.length();
        int chunkCount = length / DEFAULT_CHUNK_SIZE;
        int lastChunkSize = length % DEFAULT_CHUNK_SIZE;
        for (int i = 0; i < chunkCount; i++) {
            String startOfChunk = String.format(START_OF_CHUNK, DEFAULT_CHUNK_SIZE);
            String chunkData = message.substring(i * DEFAULT_CHUNK_SIZE, (i + 1) * DEFAULT_CHUNK_SIZE);
            chunkedMessage.append(startOfChunk).append(chunkData);
        }
        if (lastChunkSize != 0) {
            String startOfChunk = String.format(START_OF_CHUNK, lastChunkSize);
            String chunkData = message.substring(chunkCount * DEFAULT_CHUNK_SIZE);
            chunkedMessage.append(startOfChunk).append(chunkData);
        }
        return chunkedMessage.append(END_OF_CHUNK).toString();
    }
}
